package utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by liuchang on 2015/6/25.
 */
public class ImageUtils {

    /**
     * @param fis
     * @param fos
     * @param destFormat
     * @param width
     * @param height
     * @return
     * @throws Exception http://www.2cto.com/kf/201312/267934.html
     */
    public static boolean convertFormat(InputStream fis, FileOutputStream fos, String destFormat,
                                        int width, int height) throws Exception {
        boolean flag = false;
        BufferedImage src = ImageIO.read(fis);

        // compress the origin image if width and height are non-zero
        if (height > 0 && width > 0) {
            height = src.getHeight() > height ? height : src.getHeight();
            width = src.getWidth() > width ? width : src.getWidth();
            Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
            BufferedImage buf = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);

            Graphics g = buf.getGraphics();
            g.drawImage(image, 0, 0, null);

            g.dispose();
            buf.flush();
            flag = ImageIO.write(buf, destFormat, fos);
        } else {
            flag = ImageIO.write(src, destFormat, fos);
        }
        return flag;
    }
}
